// 48.旋转图像
// https://leetcode.cn/problems/rotate-image/description/

/**
示例 1：
输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出：[[7,4,1],[8,5,2],[9,6,3]]


示例 2：
输入：matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
输出：[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
 */

/**
 * 思路：
绕中心顺时针旋转90度，参考行列式变换
https://www.bilibili.com/video/BV1ms41167u9/?spm_id_from=333.788.recommend_more_video.2&vd_source=4fd973d19cb5506a7c9f2d59e8ab5165

ihat [1,0] 顺时针90度-> [0,-1] 
jhat [0,1] 顺时针90度-> [1,0]
ihat,jhat的行列式矩阵为
[  0 1 ]
[ -1 0 ]

当一个坐标绕这个点旋转，比如坐标为[x,y]

方程为
x = 0*x+1*y => y
y = -1*x +0*y => -x

 */

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var rotate = function (matrix) {
    const center = (matrix.length - 1) / 2;
    const centerExist = Number.isInteger(center);

    console.table(matrix);

    let newMatrix = new Array(matrix.length)
        .fill(0)
        .map((_) => new Array(matrix[0].length).fill(0).map((_) => 0));

    for (let row = 0; row < matrix.length; row++) {
        for (let col = 0; col < matrix.length; col++) {
            let axis_X = col - center;
            let axis_Y = center - row;

            // if (!centerExist) {
            //     axis_X = axis_X < 0 ? Math.floor(axis_X) : Math.ceil(axis_X);
            //     axis_Y = axis_Y < 0 ? Math.floor(axis_Y) : Math.ceil(axis_Y);
            // }

            [axis_X, axis_Y] = [axis_Y, -1 * axis_X];
            axis_X =
                axis_X > 0
                    ? Math.floor(center + axis_X)
                    : Math.ceil(center + axis_X);
            axis_Y =
                axis_Y > 0
                    ? Math.abs(Math.floor(axis_Y - center))
                    : Math.abs(Math.ceil(axis_Y - center));

            newMatrix[axis_Y][axis_X] = matrix[row][col];
        }
    }

    console.table(newMatrix);

    for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[0].length; j++) {
            matrix[i][j] = newMatrix[i][j];
        }
    }
};

rotate([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]); // 输出：[[7,4,1],[8,5,2],[9,6,3]])

rotate([
    [5, 1, 9, 11],
    [2, 4, 8, 10],
    [13, 3, 6, 7],
    [15, 14, 12, 16],
]); // [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]])
